package com.course.masterservice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.course.component.http.BasePageResponse;
import com.course.component.http.requ.RequestArticle;
import com.course.component.util.CopyUtil;
import com.course.component.util.DateUtils;
import com.course.component.util.SnowFlake;
import com.course.component.util.uuid.IdUtils;
import com.course.entity.Articles;
import com.course.entity.Category;
import com.course.masterservice.ArticlesMasterService;
import com.course.service.ArticlesService;
import com.course.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @Copyright: Copyright (c)  林中小鸟  All rights reserved.
 * @author: moon
 * @date: 2022/9/17 14:29
 * @Description: **********************
 */
@Service
public class ArticlesMasterServiceImpl implements ArticlesMasterService {

    @Autowired
    private ArticlesService articlesService;

    @Autowired
    private CategoryService categoryService;

    @Override
    public BasePageResponse<Articles> getPageList(RequestArticle requestArticle) {
        //QueryWrapper<Articles> queryWrapper = new QueryWrapper<>();
        //搜索逻辑
        LambdaQueryWrapper<Articles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select();

        IPage<Articles> list = articlesService.page(new Page<>(requestArticle.getPage().intValue(),requestArticle.getPageSize().intValue()),queryWrapper);
        List<Articles> records = list.getRecords();
        for(Articles item:records){
            Category cat = categoryService.getById(item.getCategoryId());
            item.setCategory(cat);
        }
        return new BasePageResponse(list.getTotal(),records);
    }

    @Override
    public Boolean del(RequestArticle requestArticle) {
        Articles updateData = CopyUtil.copy(requestArticle,Articles.class);
        updateData.setIsdel(true);
        updateData.setUpdateTime(DateUtils.getTime());
        return articlesService.updateById(updateData);
    }

    @Override
    public Boolean update(RequestArticle requestArticle) {
        Articles updateData = CopyUtil.copy(requestArticle,Articles.class);
        if(ObjectUtils.isEmpty(updateData.getId())){
            updateData.setId(new SnowFlake().nextId());
            updateData.setCreateTime(DateUtils.getTime());
        }
        updateData.setUpdateTime(DateUtils.getTime());
        return articlesService.saveOrUpdate(updateData);
    }

    @Override
    public Articles getArticle(Long id) {
        Articles articles = articlesService.getById(id);
        Category cat = categoryService.getById(articles.getCategoryId());
        articles.setCategory(cat);
        return articles;
    }
}
